package aes;

import java.util.Base64;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class UseAES {

	//初始向量
	public static final String vector="aabbccddeeffgghh";
	//编码方式
	public static final String code="UTF-8";
	//密钥
	private static final String AES_KEY="aabbccddeeffgghh";

	public static String encrypt(String plainText){
		try {
			IvParameterSpec zero=new IvParameterSpec(vector.getBytes());
			//建立私钥对象
			SecretKeySpec keySpec=new SecretKeySpec(AES_KEY.getBytes(), "AES");
			//实例化加密类
			Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
			//初始化加密类
			cipher.init(Cipher.ENCRYPT_MODE, keySpec,zero);
			byte[] encryptedData=cipher.doFinal(plainText.getBytes(code));
			return  Base64.getEncoder().encodeToString(encryptedData);
			


		} catch (Exception e) {
			// TODO: handle exception
			return "加密失败！";
		}
	}
	public static String decryption(String cipherText){
		try {
			byte[] temp=Base64.getDecoder().decode(cipherText);
			IvParameterSpec zero=new IvParameterSpec(vector.getBytes());
			SecretKeySpec keySpec=new SecretKeySpec(AES_KEY.getBytes(),"AES");
			Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE,keySpec,zero);
			byte[] result=cipher.doFinal(temp);
			return new String(result,code);
			
		} catch (Exception e) {
			// TODO: handle exception
			return "解密失败！";
		}
	}
	public static void main(String[] args) {
		String plainText="98.5674";
		String cipherText=encrypt(new String(encrypt(plainText)));
		System.out.println(cipherText);
		System.out.println("");
		System.out.println(decryption(cipherText));
	}

}
